package com.live.adapter;

import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlSerializer;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.live.activity.R;
import com.live.receiver.LiveReceiver;
import com.live.tools.LiveTools;

public class LiveMatchSimpleAdapter extends SimpleAdapter {

	private LinearLayout matchStstusView;

	private String locale = LiveTools.getLocaleLanguage();

	private Context context = null;

	private List<Map<String, Object>> items = null;

	private String date = null;

	private List<Map<String, Object>> liveAlarmList = null;

	public LiveMatchSimpleAdapter(Context context, List<Map<String, Object>> items, int resource, String[] from,
			int[] to, String date) {
		super(context, items, resource, from, to);
		this.context = context;
		this.items = items;
		this.date = date;

		// 取得现有提醒表
		liveAlarmList = LiveTools.readLiveAlarmFile(context, "alarm_" + date + ".xml".toString());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = super.getView(position, convertView, parent);
		TextView matchStstus = (TextView) view.findViewById(R.id.matchStatus);
		String matchStstusText = (String) matchStstus.getText();

		matchStstusView = (LinearLayout) view.findViewById(R.id.matchStatusView);
		if (LiveTools.tradToSimp("已结束", locale).equals(matchStstusText)) {
			matchStstusView.setBackgroundColor(Color.parseColor("#DFDFDF"));
		} else if (LiveTools.tradToSimp("未开始", locale).equals(matchStstusText)) {
			matchStstusView.setBackgroundColor(Color.parseColor("#E0F0F8"));
		} else {
			matchStstusView.setBackgroundColor(Color.parseColor("#FFD7D7"));
		}

		// 提醒按钮
		ImageView matchAlarm = (ImageView) view.findViewById(R.id.matchAlarm);
		matchAlarm.setTag(position);
		matchAlarm.setOnClickListener(new ImageView.OnClickListener() {
			public void onClick(View v) {

				Map<String, Object> match = items.get((Integer) v.getTag());

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM");
				Date time = new Date(System.currentTimeMillis());

				// 当提醒时间大于当前时间时，不给予提醒
				if (df.format(time).compareTo(match.get("matchTimeAll").toString()) > 0) {
					Toast.makeText(v.getContext(), R.string.alarm_error, Toast.LENGTH_LONG).show();
					return;
				}

				// 创建AlarmManager
				@SuppressWarnings("static-access")
				AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);

				// 指定Receiver
				Intent liveReceiverIntent = new Intent(context, LiveReceiver.class);
				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", match.get("matchId").toString());
				liveReceiverIntent.putExtras(bundle);

				// 为系统添加定时提醒
				PendingIntent pi = PendingIntent.getBroadcast(context,
						Integer.valueOf(match.get("matchId").toString()), liveReceiverIntent, 0);

				boolean addFlag = true;

				// 取得现有提醒表长度
				int liveAlarmLength = liveAlarmList.size();
				for (int i = 0; i < liveAlarmLength; i++) {
					Map<String, Object> alarm = liveAlarmList.get(i);
					
					// 如果当前比赛在现有提醒里表中存在，则删除此提醒
					if (match.get("matchId").equals(alarm.get("matchId"))) {
						
						Toast.makeText(v.getContext(), R.string.alarm_cancel, Toast.LENGTH_LONG).show();

						// 从系统中删除已经添加的定时提醒
						am.cancel(pi);

						// 重新设置提醒图片
						((ImageView) v).setImageResource(R.drawable.clock_off);
						
						// 删除此提醒
						liveAlarmList.remove(i);
						
						addFlag = false;
						break;
					}
				}

				// 如果当前比赛在现有提醒里表中不存在，则添加此提醒
				if (addFlag) {
					
					Toast.makeText(v.getContext(), R.string.alarm_add, Toast.LENGTH_LONG).show();

					// 往系统中添加提醒时间
					String matchTime = String.valueOf(match.get("matchTimeAll"));
					matchTime = matchTime.replaceAll("-", ",");
					matchTime = matchTime.replaceAll(" ", ",");
					matchTime = matchTime.replaceAll(":", ",");
					String matchTims[] = matchTime.split(",");
					Calendar c = Calendar.getInstance();
					c.set(Integer.valueOf(matchTims[0]), Integer.valueOf(matchTims[1]) - 1,
							Integer.valueOf(matchTims[2]), Integer.valueOf(matchTims[3]),
							Integer.valueOf(matchTims[4]), 0);
					// c.set(2012, 2, 7, 17, 8, 0);
					am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);

					// 重新设置提醒图片
					((ImageView) v).setImageResource(R.drawable.clock_on);

					// 添加此提醒
					liveAlarmList.add(match);
				}

				if (liveAlarmList.size() == 0) {
					LiveTools.deleteFile(context, "alarm_", null);
				} else {
					// 写入本机缓存数据（XML）
					LiveTools.writeFile(context, "alarm_" + date + ".xml".toString(), buildXml(liveAlarmList));
				}
			}
		});

		Map<String, Object> match = items.get(position);
		for (int i = 0; i < liveAlarmList.size(); i++) {
			Map<String, Object> alarm = liveAlarmList.get(i);
			// 如果当前比赛在现有提醒里表中存在
			if (match.get("matchId").equals(alarm.get("matchId"))) {
				// 重新设置提醒图片
				matchAlarm.setImageResource(R.drawable.clock_on);
				break;
			} else {
				matchAlarm.setImageResource(R.drawable.clock_off);
			}
		}
		return view;
	}

	private String buildXml(List<Map<String, Object>> matchList) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);

			// <?xml version="1.0″ encoding="UTF-8″ standalone="yes"?>
			serializer.startDocument("UTF-8", true);
			// <liveScore number="1″>
			serializer.startTag(null, "matchs");
			for (int i = 0; i < matchList.size(); i++) {
				Map<String, Object> match = matchList.get(i);

				// <detail>
				serializer.startTag(null, "match");

				// <matchId>
				serializer.startTag(null, "matchId");
				serializer.text(String.valueOf(match.get("matchId")));
				serializer.endTag(null, "matchId");

				// <matchTime>
				serializer.startTag(null, "matchTime");
				String matchTime = String.valueOf(match.get("matchTimeAll"));
				matchTime = matchTime.replaceAll("-", ",");
				matchTime = matchTime.replaceAll(" ", ",");
				matchTime = matchTime.replaceAll(":", ",");
				serializer.text(matchTime);
				serializer.endTag(null, "matchTime");

				// <matchName>
				serializer.startTag(null, "matchName");
				String matchName = String.valueOf(match.get("matchName"));
				serializer.text(matchName);
				serializer.endTag(null, "matchName");

				// <homeTeam>
				serializer.startTag(null, "homeTeam");
				String homeTeam = String.valueOf(match.get("homeTeam"));
				serializer.text(homeTeam);
				serializer.endTag(null, "homeTeam");

				// <visitTeam>
				serializer.startTag(null, "visitTeam");
				String visitTeam = String.valueOf(match.get("visitTeam"));
				serializer.text(visitTeam);
				serializer.endTag(null, "visitTeam");

				// <homeTeamPic>
				serializer.startTag(null, "homeTeamPic");
				String homeTeamPic = String.valueOf(match.get("homeTeamPic"));
				serializer.text(homeTeamPic);
				serializer.endTag(null, "homeTeamPic");

				// <visitTeamPic>
				serializer.startTag(null, "visitTeamPic");
				String visitTeamPic = String.valueOf(match.get("visitTeamPic"));
				serializer.text(visitTeamPic);
				serializer.endTag(null, "visitTeamPic");

				serializer.endTag(null, "match");
			}
			serializer.endTag(null, "matchs");
			serializer.endDocument();

			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
